#include "mainwindow.h"
#include "ui_mainwindow.h"


// 
void MainWindow::Gui_Init_CFG()
{
    // 计数初始化
    CheckSum_Cfg = 0;
    CheckCnt_Cfg = 0;

    // 设置表格列数
    QString TypeKey = "type/time";
    int TypeTime = CfgFile_Dlbox->value(TypeKey).toInt();
    ui->tw_title_cfg->setColumnCount(TypeTime);
    ui->tw_title_cfg->setRowCount(1);
    ui->tw_cont_cfg->setColumnCount(TypeTime);
    // 设置表头
    QStringList TitleStr;
    TitleStr.clear();
    //
    TypeList_Cfg.clear();
    for(int j=0;j<TypeTime;j++)
    {
        // name INI配置
        QString NameKey = "type/name" + QString::number(j);
        // 添加复选框
        QCheckBox *checkbox = new QCheckBox();
        QString TitleName = CfgFile_Dlbox->value(NameKey).toString();
        checkbox->setText(TitleName);
        TypeList_Cfg.append(TitleName);
        checkbox->setCheckState(Qt::Unchecked);
        checkbox->setEnabled(false);
        QFont font;
        font.setFamily("Microsoft YaHei");
        font.setPointSize(14);
        font.setBold(true);
        checkbox->setFont(font);
        checkbox->setStyleSheet("QCheckBox{background-color:#9FD9F6;}") ;
        connect(checkbox,SIGNAL(clicked()),this,SLOT(tw_title_cfg_checkbox_statechanged()));
        //增加widget+布局巧妙实现居中
        QWidget *widget = new QWidget();
        QHBoxLayout *layout = new QHBoxLayout();
        layout->setMargin(0);//一定要有
        QLabel *SpalceLbl = new QLabel();
        SpalceLbl->setMinimumSize(QSize(10,10));
        SpalceLbl->setMaximumSize(QSize(10,10));
        layout->addWidget(SpalceLbl);
        layout->addWidget(checkbox);
//        layout->setAlignment(checkbox, Qt::AlignCenter);//控件在布局中居中显示
        widget->setLayout(layout);
        ui->tw_title_cfg->setCellWidget(0, j, widget);
    }
    // 设置表头属性
    ui->tw_title_cfg->setEditTriggers(QAbstractItemView::NoEditTriggers); //不允许编辑
    ui->tw_title_cfg->setSelectionMode(QAbstractItemView::NoSelection); //不允许选中
    ui->tw_title_cfg->horizontalHeader()->setVisible(false);    // 列表头不可见
    ui->tw_title_cfg->verticalHeader()->setVisible(false);      // 行表头不可见
    ui->tw_title_cfg->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);   // 行拉伸
    ui->tw_title_cfg->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);     // 列拉伸
    ui->tw_title_cfg->setShowGrid(false);   //表格线不可见
    ui->tw_title_cfg->setStyleSheet("QTableWidget{background-color:#9FD9F6}"
                                    "QTableWidget::item:hover{background-color:#9FD9F6;};") ;
    // 设置内容属性
    ui->tw_cont_cfg->setEditTriggers(QAbstractItemView::NoEditTriggers); //不允许编辑
    ui->tw_cont_cfg->setSelectionMode(QAbstractItemView::NoSelection); //不允许选中
    ui->tw_cont_cfg->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);   // 行拉伸
    ui->tw_cont_cfg->verticalHeader()->setVisible(false);      // 行表头不可见
    //    ui->tw_cont_cfg->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);     // 列拉伸
    // ui->tw_cont_cfg->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    ui->tw_cont_cfg->setShowGrid(false);    //表格线不可见
//    ui->tw_cont_cfg->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);    //隐藏垂直滚动条
    ui->tw_cont_cfg->setStyleSheet(
    "QTableWidget::Item{border:0px solid rgb(182,182,182);"
    "border-left:0.5px solid rgb(182,182,182);"
    "border-right:0.5px solid rgb(182,182,182);}"
    );
}

// 选择目标路径
void MainWindow::on_btn_file_read_cfg_clicked()
{
    // 选择路径
    QString OpenFilePath = ui->te_file_read_cfg->toPlainText();
    QString TempFilePath = App_Btn_ChoosePath_GetPath("OpenDir_CFG");
    if(TempFilePath.isEmpty())
    {
        ui->te_file_read_cfg->setText(OpenFilePath);
    }
    else
    {
        ui->te_file_read_cfg->setText(TempFilePath);
    }
}
// 文本更改后进行遍历
void MainWindow::on_te_file_read_cfg_textChanged()
{
    // 检查路径是否为文件夹
    QString OpenFilePath = ui->te_file_read_cfg->toPlainText();
	if(OpenFilePath.isEmpty())
	{
		return;
	}
	QFileInfo File(OpenFilePath);
    if(File.isDir())
    {
        // 遍历文件目录
        QDirIterator iter(OpenFilePath, QDirIterator::Subdirectories);
        QStringList ImgList;
        ImgList.clear();
        while (iter.hasNext())
        {
            iter.next();
            QFileInfo info = iter.fileInfo();
            if (info.isFile())
            {
                QString FileName = info.absoluteFilePath();
                // 检索后缀名为ibm的文件
                if(info.suffix() == "ibm")
                {
                    ImgList.append(FileName.mid(FileName.lastIndexOf('/')+1));
                }
            }
        }
        //对图片文件列表进行排序（控制升级顺序）
        QString TmpString;
        for(int i=0;i<ImgList.size()-1;i++)
        {
            for(int j=i+1;j<ImgList.size();j++)
            {
                if(ImgList.at(i) > ImgList.at(j))
                {
                    TmpString = ImgList.at(i);
                    ImgList[i] = ImgList.at(j);
                    ImgList[j] = TmpString;
                }
            }
        }
        //清空表内容
        for(int i=0;i<ui->tw_cont_cfg->rowCount();)
            ui->tw_cont_cfg->removeRow(i);
        //表头取消勾选
        for(int i=0;i<ui->tw_title_cfg->columnCount();i++)
        {
            QWidget *widget = new QWidget();
            widget = ui->tw_title_cfg->cellWidget(0, i);
            QCheckBox *CheckboxTitle = widget->findChild<QCheckBox *>();
            CheckboxTitle->setChecked(false);
        }
        //删除数据库所有数据
        while(SqlMode->rowCount() != 0)
        {
            SqlMode->removeRows(0, SqlMode->rowCount());
            SqlMode->submitAll();
        }
        //添加复选框
        CheckSum_Cfg = 0;
        for(int i=0;i<ImgList.size();i++)
        {
            // 根据图片文件名称读取配置文件键值对
            QString FileName = ImgList.at(i);
            QString TimeKey = FileName + "/time";
            int TimeNum = CfgFile_Dlbox->value(TimeKey).toInt();
            // 配置文件
            for(int j=0;j<TimeNum;j++)
            {
                // name INI配置
                QString NameKey = FileName + "/name" + QString::number(j);
                QString NameStr = CfgFile_Dlbox->value(NameKey).toString();
                QString ModeKey = FileName + "/mode" + QString::number(j);
                QString ModeStr = CfgFile_Dlbox->value(ModeKey).toString();
                QString TypeKey = FileName + "/type" + QString::number(j);
                QString TypeStr = CfgFile_Dlbox->value(TypeKey).toString();

                //数据添加数据库
                int rowNum = SqlMode->rowCount();
                // 添加一行
                SqlMode->insertRow(rowNum);
                if(NameStr == "hwMT10P")
                {
                    NameStr = "hwMT10P";
                }
                SqlMode->setData(SqlMode->index(rowNum,0),rowNum);
                SqlMode->setData(SqlMode->index(rowNum,1),NameStr);
                SqlMode->setData(SqlMode->index(rowNum,2),TypeStr);
                SqlMode->setData(SqlMode->index(rowNum,3),FileName);
                SqlMode->setData(SqlMode->index(rowNum,4),ModeStr);
                SqlMode->setData(SqlMode->index(rowNum,5),0);
                SqlMode->submitAll();
                CheckSum_Cfg = rowNum;

                //表内添加复选框
                // 查询类型为第几列
                int ColumnNum=0;
                for(ColumnNum=0;ColumnNum<TypeList_Cfg.size();ColumnNum++)
                {
                    if(TypeList_Cfg.at(ColumnNum) == TypeStr)
                    {
                        break;
                    }
                }
                // 查询该列第几行无复选框
                int RowNum = -1;
                for(int iCnt=0;iCnt<ui->tw_cont_cfg->rowCount();iCnt++)
                {
                    QWidget *widget = new QWidget();
                    widget = ui->tw_cont_cfg->cellWidget(iCnt, ColumnNum);
                    if(widget == nullptr)
                    {
                        RowNum = 1;
                        // 修改行
                        tw_cont_cfg_checkbox_add(NameKey, iCnt, ColumnNum);
                        break;
                    }
                }
                //插入行
                if(RowNum == -1)
                {
                    rowNum = ui->tw_cont_cfg->rowCount();
                    ui->tw_cont_cfg->insertRow(rowNum);
                    ui->tw_cont_cfg->setRowHeight(rowNum, 30);
                    tw_cont_cfg_checkbox_add(NameKey, rowNum, ColumnNum);
                }
            }
        }
        for(int TitleCnt=0;TitleCnt<ui->tw_title_cfg->columnCount();TitleCnt++)
        {
            // 判断当前单元格有无复选框
            QWidget *widget = new QWidget();
            widget = ui->tw_title_cfg->cellWidget(0, TitleCnt);
            if(widget != nullptr)
            {
                // 设置复选框选中|不选
                QCheckBox *CheckboxCont = widget->findChild<QCheckBox *>();
                // 判断当前单元格有无复选框
                QWidget *ContWidget = new QWidget();
                ContWidget = ui->tw_cont_cfg->cellWidget(0, TitleCnt);
                if(ContWidget != nullptr)
                {
                    CheckboxCont->setEnabled(true);
                }
                else
                {
                    CheckboxCont->setEnabled(false);
                }
            }
        }
    }
}
// 添加单个复选框
void MainWindow::tw_cont_cfg_checkbox_add(QString NameKey, int row, int column)
{
    // 添加复选框
    QCheckBox *checkbox = new QCheckBox();
    QString TitleName = CfgFile_Dlbox->value(NameKey).toString();
    checkbox->setText(TitleName);
    checkbox->setCheckState(Qt::Unchecked);
    connect(checkbox,SIGNAL(clicked()),this,SLOT(tw_cont_cfg_checkbox_statechanged()));
    //增加widget+布局巧妙实现居中
    QWidget *widget = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout();
    layout->setMargin(0);//一定要有
    QLabel *SpalceLbl = new QLabel();
    SpalceLbl->setMinimumSize(QSize(10,10));
    SpalceLbl->setMaximumSize(QSize(10,10));
    layout->addWidget(SpalceLbl);
    layout->addWidget(checkbox);
//    layout->setAlignment(checkbox, Qt::AlignCenter);//控件在布局中居中显示
    widget->setLayout(layout);
    ui->tw_cont_cfg->setCellWidget(row, column, widget);
}
// 表头全选|全不选
void MainWindow::tw_title_cfg_checkbox_statechanged()
{
    // 获取选中复选框的列
    QCheckBox *CheckboxTitle = qobject_cast<QCheckBox*>(sender());
    if(CheckboxTitle == nullptr)
    {
        return;
    }
    QModelIndex IdxTitle = ui->tw_title_cfg->indexAt(QPoint(CheckboxTitle->parentWidget()->frameGeometry().x(),CheckboxTitle->parentWidget()->frameGeometry().y()));
    int ColumnNum = IdxTitle.column();
    bool CheckedStu = CheckboxTitle->isChecked();
    //
    int CountNum = ui->tw_cont_cfg->rowCount();
    if(CountNum == 0)
    {
        if(CheckedStu == true)
        {
            CheckboxTitle->setChecked(false);
        }
        return;
    }
    for(int i=0;i<CountNum;i++)
    {
        // 判断当前单元格有无复选框
        QWidget *widget = new QWidget();
        widget = ui->tw_cont_cfg->cellWidget(i, ColumnNum);
        if(widget == NULL)
        {
            break;
        }
        else
        {
            // 设置复选框选中|不选
            QCheckBox *CheckboxCont = widget->findChild<QCheckBox *>();
            if(CheckedStu == true)
            {
                if(CheckboxCont->isChecked() == false)
                {
                    CheckboxCont->setChecked(true);
                }
            }
            else
            {
                if(CheckboxCont->isChecked() == true)
                {
                    CheckboxCont->setChecked(false);
                }
            }
        }
    }
    QString TypeName = CheckboxTitle->text();
    QSqlTableModel SqlMode_Cfg;
    SqlMode_Cfg.setTable("configure");
    SqlMode_Cfg.setFilter(QString("type='%1'").arg(TypeName));
    SqlMode_Cfg.select();
    if(CheckedStu == true)
    {
        for(int i=0; i<SqlMode_Cfg.rowCount(); i++)
        {
            SqlMode_Cfg.setData(SqlMode_Cfg.index(i, 5), 1);
            SqlMode_Cfg.submitAll();
            CheckCnt_Cfg++;
            // 勾选 模式和文件相同的项
            tw_cont_cfg_checkbox_inline_statechanged(&SqlMode_Cfg,i,CheckedStu);
        }
    }
    else
    {
        for(int i=0; i<SqlMode_Cfg.rowCount(); i++)
        {
            SqlMode_Cfg.setData(SqlMode_Cfg.index(i, 5), 0);
            SqlMode_Cfg.submitAll();
            CheckCnt_Cfg--;
            // 去掉勾选 模式和文件相同的项
            tw_cont_cfg_checkbox_inline_statechanged(&SqlMode_Cfg,i,CheckedStu);
        }
    }
}
// 内容复选框 勾选|取消勾选
void MainWindow::tw_cont_cfg_checkbox_statechanged()
{
    // 获取选中复选框的列
    QCheckBox *CheckboxCont = qobject_cast<QCheckBox*>(sender());
    if(CheckboxCont == nullptr)
    {
        return;
    }
    QModelIndex IdxCont = ui->tw_cont_cfg->indexAt(QPoint(CheckboxCont->parentWidget()->frameGeometry().x(),CheckboxCont->parentWidget()->frameGeometry().y()));
    int ColumnNum = IdxCont.column();
    // 加入数据库
    QString TypeName = CheckboxCont->text();
    QSqlTableModel SqlMode_Cfg;
    SqlMode_Cfg.setTable("configure");
    SqlMode_Cfg.setFilter(QString("name='%1'").arg(TypeName));
    SqlMode_Cfg.select();
    if(CheckboxCont->isChecked())
    {
        SqlMode_Cfg.setData(SqlMode_Cfg.index(0, 5), 1);
        SqlMode_Cfg.submitAll();
        CheckCnt_Cfg++;
    }
    else
    {
        SqlMode_Cfg.setData(SqlMode_Cfg.index(0, 5), 0);
        SqlMode_Cfg.submitAll();
        CheckCnt_Cfg--;
    }
    // 勾选|去掉勾选 模式和文件相同的项
    tw_cont_cfg_checkbox_inline_statechanged(&SqlMode_Cfg,0,CheckboxCont->isChecked());
}
// 单个内容复选框关联的所有复选框 勾选|取消勾选
void MainWindow::tw_cont_cfg_checkbox_inline_statechanged(QSqlTableModel* SqlMode_Cfg, int RowNum, bool CheckStu)
{
    int iCheck = 1;
    if(CheckStu)
    {
        iCheck = 0;
    }
    // 勾选 模式和文件相同的项
    QSqlRecord RecordVal = SqlMode_Cfg->record(RowNum);
    QString FileName = RecordVal.value(3).toString();
    QString ModeStr = RecordVal.value(4).toString();
    int Checked = iCheck;
    QSqlTableModel SqlMode_Inline;
    SqlMode_Inline.setTable("configure");
    SqlMode_Inline.setFilter(QString("filename='%1' and mode='%2' and checked='%3'").arg(FileName).arg(ModeStr).arg(Checked));
    SqlMode_Inline.select();
    for(int i=0;i<SqlMode_Inline.rowCount();i++)
    {
        //取相同项的name和type值
        RecordVal = SqlMode_Inline.record(i);
        QString NameStr = RecordVal.value(1).toString();
        QString TypeStr = RecordVal.value(2).toString();
        //根据name和type查找单元格位置
        for (int TitleCnt=0;TitleCnt<ui->tw_title_cfg->columnCount();TitleCnt++)
        {
            //单元格所在列数
            QWidget *widget = new QWidget();
            widget = ui->tw_title_cfg->cellWidget(0, TitleCnt);
            QCheckBox *CheckboxTitle = widget->findChild<QCheckBox *>();
            if(CheckboxTitle->text() == TypeStr)
            {
                //单元格所在行数
                int j=0;
                for(j=0;j<ui->tw_cont_cfg->rowCount();j++)
                {
                    //单元格所在列数
                    QWidget *widget = new QWidget();
                    widget = ui->tw_cont_cfg->cellWidget(j, TitleCnt);
                    if(widget == nullptr)
                    {
                        j = ui->tw_cont_cfg->rowCount();
                        break;
                    }
                    QCheckBox *CheckboxCont = widget->findChild<QCheckBox *>();
                    if(CheckboxCont->text() == NameStr)
                    {
                        CheckboxCont->setChecked(CheckStu);
                        SqlMode_Inline.setData(SqlMode_Inline.index(i, 5), !iCheck);
                        SqlMode_Inline.submitAll();
                        if(CheckStu)
                        {
                            CheckCnt_Cfg++;
                        }
                        else
                        {
                            CheckCnt_Cfg--;
                        }
                        j = ui->tw_cont_cfg->rowCount();
                        break;
                    }
                }
                if(j == ui->tw_cont_cfg->rowCount())
                {
                    break;
                }
            }
        }
    }
    tw_title_cfg_CheckState();
}
// 检查表头状态
void MainWindow::tw_title_cfg_CheckState()
{
    // 获取表头复选框状态
    for(int TitleNum=0;TitleNum<ui->tw_title_cfg->columnCount();TitleNum++)
    {
        QWidget *widget = new QWidget();
        widget = ui->tw_title_cfg->cellWidget(0, TitleNum);
        QCheckBox *CheckboxTitle = widget->findChild<QCheckBox *>();
        bool CheckedStu = CheckboxTitle->isChecked();
        // 遍历所有复选框
        int CountNum = ui->tw_cont_cfg->rowCount();
        int i=0;
        for(i=0;i<CountNum;i++)
        {
            // 判断当前单元格有无复选框
            QWidget *widget = new QWidget();
            widget = ui->tw_cont_cfg->cellWidget(i, TitleNum);
            if(widget == nullptr)
            {
                break;
            }
            else
            {
                // 如果复选框取消选中，设置表头复选框为全不选
                QCheckBox *CheckboxCont = widget->findChild<QCheckBox *>();
                if(CheckboxCont->isChecked() == false)
                {
                    if(CheckedStu == true)
                    {
                        CheckboxTitle->setChecked(false);
                    }
                    i = 0;
                    break;
                }
            }
        }
        // 如果所有复选框都勾选，设置表头复选框为全选
        if(i != 0)
        {
            CheckboxTitle->setChecked(true);
        }
    }
}
